package com.wangmeng.book.server.action;

import com.wangmeng.book.job.JobExecutorHelper;
import com.wangmeng.book.server.Command;
import com.wangmeng.book.server.CommandResult;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * User: 王猛
 * Date: 13-10-1
 */
public class JobManageAction implements IBaseAction {
    public CommandResult execute(Command cmd) {
        CommandResult cr = new CommandResult();
        try {
            int ct = cmd.getCmdCode();
            Map<String, Object> cmdData = cmd.getData();
            if (ct == Command.CMD_JOB_START) {
                if (cmdData != null) {
                    Integer jt = (Integer) cmdData.get("job_type");
                    if (jt != null) {
                        Integer delay = (Integer) cmdData.get("delay");
                        Integer period = (Integer) cmdData.get("period");
                        TimeUnit unit = (TimeUnit) cmdData.get("unit");
                        if (delay == null) {
                            delay = 0;
                        }
                        if (period == null) {
                            period = 0;
                        }
                        if (unit == null) {
                            unit = TimeUnit.SECONDS;
                        }
                        cr.setCode(JobExecutorHelper.getExecutorHelper().startJobByType(jt, delay, period, unit));
                    }
                }
            } else if (ct == Command.CMD_JOB_STOP) {
                if (cmdData != null) {
                    Integer jt = (Integer) cmdData.get("job_type");
                    if (jt != null) {
                        cr.setCode(JobExecutorHelper.getExecutorHelper().stopJobByType(jt));
                    }
                }
            } else if (ct == Command.CMD_JOB_SHUTDOWN) {
                JobExecutorHelper.getExecutorHelper().close();
            }
        } catch (Exception ex) {
            cr.setCode(CommandResult.CODE_COMMON_ERROR);
            cr.setMessage(ex.getMessage());
        }
        return cr;
    }
}
